<template>
    <LayOut :bread="[{
        url: '/course',
        title: '课程',
    }, {
        title: '新增课程',
    }]">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" label-width="auto" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="标题" prop="title" required>
                <el-input v-model="ruleForm.title" clearable />
            </el-form-item>
            <el-form-item label="分类" prop="classify" required>
                <el-select v-model="ruleForm.classify" placeholder="请选择分类">
                    <el-option v-for="item in classify" :key="item.id" :label="item.label" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="说明" prop="desc" required>
                <el-input v-model="ruleForm.desc" type="textarea" :rows="3" clearable />
            </el-form-item>
            <el-form-item label="上传视频" prop="url" required>
                <el-upload class="upload-demo" :headers="headers" method="post" drag :action="actionUrl" multiple
                    :on-exceed="handleExceed" ref="upload" :limit="1" :auto-upload="true" :before-upload="beforeUpload"
                    :on-success="onSuccess" :on-error="onError">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">
                        Drop file here or <em>click to upload</em>
                    </div>
                    <template #tip>
                        <div class="el-upload__tip">
                            请上传视频，视频文件不超过 500MB
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    创建
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>

        </el-form>
    </LayOut>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router';
import type { ComponentSize, FormInstance, UploadProps, UploadInstance, UploadRawFile } from 'element-plus'
import LayOut from '../components/LayOut.vue'
import { ElMessage } from 'element-plus'
import service from '../service/index'
import { to, getCookie } from '../plugin/index'
import type { RuleForm } from '../type'
import { useAuthorizationStore } from '../stores/authorization';

const userStore = useAuthorizationStore();
const router = useRouter();

const { uploadVideo, createCourse } = service;

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
    title: '',
    classify: 1,
    desc: '',
    url: '',
})
const actionUrl = ref<string>('');
const headers = ref({});

const classify = ref<{
    id: number;
    label: string;
}[]>([{
    id: 1,
    label: '账号模块',
}, {
    id: 2,
    label: '操作教程',
}, {
    id: 3,
    label: '创作中心',
}, {
    id: 4,
    label: '常见问题',
}])

const tagArr = ref<{ id: string, label: string, value: number }[]>([]);
const label = ref('')
const upload = ref<UploadInstance>()

const createCourseHandle = async () => {
    console.log(ruleForm);
    const [res, err] = await to(createCourse({ ...ruleForm }));
    // loading.close();
    const result = res.data;
    if (!err && result.code === 1) {
        ElMessage.success(result.msg);
        router.push('/course');
    } else {
        ElMessage.error('新增失败');
        console.error(err);
    }
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            createCourseHandle();
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields();
    upload.value?.clearFiles();
    ruleForm.url = '';
}

const handleExceed: UploadProps['onExceed'] = (files) => {
    ElMessage.error('上传超限，想要更新视频请删除再重新上传');
}

const beforeUpload = (rawFile: UploadRawFile) => {
    const allowedMimeTypes = ['video/mp4', 'video/ogg', 'video/webm', 'video/x-msvideo', 'video/x-ms-wmv', 'video/mpeg'];
    const { type, size } = rawFile;
    if (!allowedMimeTypes.includes(type)) {
        ElMessage.error('请上传视频');
        return false;
    }
    const maxSizeBytes = 500 * 1024 * 1024;
    if (size > maxSizeBytes) {
        ElMessage.error('上传视频应小于 500 MB');
        return false;
    }
}

const onSuccess = (response: any) => {
    console.log(response);
    ElMessage.success(response.message);
    ruleForm.url = (response as any).data.url;
}

const onError = (error: Error) => {
    console.log(error);
    ElMessage.error(error.message);
}

onMounted(() => {
    // getTagsHandle();
    actionUrl.value = '/api/video/upload';
    headers.value = {
        Authorization: `${userStore.authorization}`,
        'x-csrf-token': getCookie('csrfToken')
    };

})
</script>

<style scoped>
.el-descriptions {
    /* margin-top: 20px; */
}

.cell-item {
    display: flex;
    align-items: center;
}

.margin-top {
    /* margin-top: 20px; */
}

.func {
    display: flex;
    justify-content: end;
    padding: 20px;
}
</style>